package cn.elead.chaos.email.template.freemarker;

import java.io.IOException;
import java.io.StringReader;

import org.apache.commons.lang.StringUtils;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;

import cn.elead.chaos.email.domain.CustomMailMessage;
import cn.elead.chaos.email.template.TemplateProcess;

import freemarker.template.Template;
import freemarker.template.TemplateException;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class FreemarkerProcess implements TemplateProcess{

	public String convertTemplate(CustomMailMessage message) {

		String text = message.getText();
		if (StringUtils.isEmpty(text)) {
			return StringUtils.EMPTY;
		}
		try {
			// 创建一个模板对象
			Template template = new Template(null, new StringReader(text), null);
			text = FreeMarkerTemplateUtils.processTemplateIntoString(template, message.getVariables());
			message.setText(text);
		} catch (IOException | TemplateException e) {
			log.error(e.getMessage(), e);
		}

		return text;
	}
}
